<template>
  <div class="player" v-show="playlist.length>0">
    <transition name="normal" v-on:enter="enter" v-on:after-enter="afterEnter" v-on:leave="leave" v-on:after-leave="afterLeave"
      v-on:leaveCancelled="afterLeave">
      <div class="normal-player" v-show="fullScreen">
        <div class="bg-filter" :style="{backgroundImage:'url('+currentSong.image+')'}"></div>
        <mu-appbar class="appbar-header">
          <mu-icon-button icon="keyboard_arrow_down" slot="left" @click="back" />
          <div class="title">
            <h3>{{currentSong.name}} ({{currentSong.album}})</h3>
            <p>{{currentSong.singer}}</p>
          </div>
        </mu-appbar>
        <div class="normal-player-main">
          <div class="song-wrap">
            <div class="record"
            @touchstart.prevent="recordStart"
            @touchmove.prevent="recordMove"
            @touchend="recordEnd">
              <div class="record-left">
                <div class="song-disc">
                  <div class="song-turn" :class="cdCls" :style="{backgroundImage:'url('+disc+')'}">
                    <div class="song-img" ref="cdWrapper">
                      <img :src="currentSong.image" />
                    </div>
                  </div>
                  <div class="song-plybtn" :style="{backgroundImage:'url('+play+')'}" v-show="!playing">
                  </div>
                </div>
              </div>
              <scroll class="record-right" ref="lyricScroll" :data="currentLyric && currentLyric.lines">
                <div class="song-lyric" v-if="currentLyric">
                  <p v-for="(line,index) in currentLyric.lines" 
                  ref="lyricLine"
                  :class="{'current':currentLineNum==index}">{{line.txt}}</p>
                </div>
              </scroll>
            </div>
            <div class=""></div>
            <div class="song-slider">
              <p>{{format(currentTime)}}</p>
              <mu-slider v-model="currentTime" @change="sliderChange" :max="currentSong.duration" :step="1" class="demo-slider" />
              <p>{{format(currentSong.duration)}}</p>
            </div>
          </div>
          <div class="player-toolds">
            <mu-flexbox class="toolds">
              <mu-flexbox-item class="flex-demo">
                <div @click="changeMode">
                  <mu-icon-menu :touch="true" :icon="iconMode" />
                </div>
              </mu-flexbox-item>
              <mu-flexbox-item class="flex-demo">
                <div @click="prev">
                  <mu-icon-menu icon="skip_previous" />
                </div>
              </mu-flexbox-item>
              <mu-flexbox-item class="flex-demo">
                <div @click="togglePlaying">
                  <mu-icon-menu :icon="playIcon" />
                </div>
              </mu-flexbox-item>
              <mu-flexbox-item class="flex-demo">
                <div @click="next">
                  <mu-icon-menu icon="skip_next" />
                </div>
              </mu-flexbox-item>
              <mu-flexbox-item class="flex-demo">
                <mu-icon-menu icon="playlist_play" />
              </mu-flexbox-item>
            </mu-flexbox>
          </div>
        </div>
      </div>
    </transition>
    <transition name="mini">
      <div class="mini-player" v-show="!fullScreen" @click.stop="open">
        <mu-paper>
          <mu-linear-progress mode="determinate" :value="currentTime" :max="currentSong.duration" />
          <mu-bottom-nav>
            <div class="mini-flex">
              <div class="song-img">
                <mu-avatar :src="currentSong.image" :class="cdCls">
                </mu-avatar>
              </div>
              <div class="song-info">
                <p>{{currentSong.name}}</p>
                <p>{{currentSong.singer}}</p>
              </div>
              <div class="toolds" @click.stop="togglePlaying">
                <mu-icon-menu :icon="miniIcon" />
              </div>
            </div>
          </mu-bottom-nav>
        </mu-paper>
      </div>
    </transition>
    <audio ref="audio" id="audio" :src="currentSong.url" @canplay="ready" autoplay="autoplay" @error="error" @timeupdate="updatetime"
      @ended="end"></audio>
  </div>
</template>
<script>
  import disc from "@/assets/image/disc-ip6.png"
  import play from "@/assets/image/play.png"
  import animations from "create-keyframe-animation"
  import scroll from "@/base/scroll"
  import {
    shuffle
  } from "@/assets/js/util"
  import lyricParser from 'lyric-parser'
  import {
    playMode
  } from "@/assets/js/config"
  import {
    prefixStyle
  } from "@/assets/js/dom"
  const Transform = prefixStyle("transform")
  import {
    mapGetters,
    mapMutations
  } from "vuex"
  export default {
    name: "component_name",
    data() {
      return {
        disc,
        play,
        songReady: false,
        currentTime: 0,
        mytimer: null,
        currentLyric: null,
        currentLineNum:0,
        currentShow:"cd"
      };
    },
    methods: {
      ...mapMutations({
        setFullScreen: "SET_FULL_SCREEN",
        setPlayState: "SET_PLAYING_STATE",
        setCurrentIndex: "SET_CURRENT_INDEX",
        setPlayMode: "SET_PLAY_MODE",
        setPlayList: "SET_PLAYLIST"
      }),
      back() {
        this.setFullScreen(false)
      },
      open() {
        this.setFullScreen(true)
      },
      enter(el, done) {
        const {
          x,
          y,
          scale
        } = this._getPosAndScale()
        let animation = {
          "0": {
            transform: `translate3d(${x}px,${y}px,0) scale(${scale})`
          },
          "60": {
            transform: `translate3d(0,0,0) scale(1.1)`
          },
          "100": {
            transform: `translate3d(0,0,0) scale(1)`
          }
        }
        animations.registerAnimation({
          name: 'move',
          animation,
          presets: {
            duration: 400,
            easing: 'linear'
          }
        })
        animations.runAnimation(this.$refs.cdWrapper, 'move', done)
      },
      afterEnter() {
        animations.unregisterAnimation('move')
        this.$refs.cdWrapper.style.animation = ''
      },
      leave(el, done) {
        this.$refs.cdWrapper.style.transition = 'all 0.4s'
        const {
          x,
          y,
          scale
        } = this._getPosAndScale()
        this.$refs.cdWrapper.style[Transform] = `translate3d(${x}px,${y}px,0) scale(${scale})`
        this.$refs.cdWrapper.addEventListener('transitionend', done)
      },
      afterLeave() {
        this.$refs.cdWrapper.style.transition = ''
        this.$refs.cdWrapper.style[Transform] = ''
      },
      _getPosAndScale() {
        const targetWidth = 40
        const paddingLeft = 40
        const paddingBottom = 28
        const paddingTop = 76
        const width = window.innerWidth * 0.8
        const scale = targetWidth / width
        const x = -(window.innerWidth / 2 - paddingLeft)
        const y = window.innerHeight - paddingTop - width / 2 - paddingBottom
        return {
          x,
          y,
          scale
        }
      },
      //播放
      togglePlaying() {
        this.setPlayState(!this.playing)
      },
      // 上一首
      prev() {
        if (!this.songReady) {
          return
        }
        let index = this.currentIndex - 1
        if (index === -1) {
          index = this.playlist.length - 1
        }
        this.setCurrentIndex(index)
        if (!this.playing) {
          this.togglePlaying()
        }
        this.songReady = false
      },
      //播放结束
      end() {
        if (this.mode === playMode.loop) {
          this.loop()
        } else {
          this.next()
        }
      },
      loop() {
        this.$refs.audio.currentTime = 0
        this.$refs.audio.play()
      },
      // 下一首
      next() {
        if (!this.songReady) {
          return
        }
        let index = this.currentIndex + 1
        if (index === this.playlist.length) {
          index = 0
        }
        this.setCurrentIndex(index)
        if (!this.playing) {
          this.togglePlaying()
        }
        this.songReady = false
      },
      ready() {
        this.songReady = true
      },
      error() {
        this.songReady = true
      },
      updatetime(e) {
        this.currentTime = parseInt(e.target.currentTime)
      },
      format(interval) {
        interval = interval | 0
        const minute = interval / 60 | 0
        const second = this._pad(interval % 60)
        return minute + ":" + second
      },
      _pad(num, n = 2) {
        let len = num.toString().length
        while (len < n) {
          num = '0' + num
          len++
        }
        return num
      },
      sliderChange(newval) {
        var that = this
        that.$refs.audio.currentTime = newval
        if (this.playing) {
          this.togglePlaying()
        }
        if (that.mytimer) {
          clearTimeout(that.mytimer)
        }
        that.mytimer = setTimeout(function () {
          if (!this.playing) {
            that.togglePlaying()
          }
        }, 300)
      },
      changeMode() {
        const mode = (this.mode + 1) % 3
        this.setPlayMode(mode)
        let list = null
        if (mode === playMode.random) {
          list = shuffle(this.sequenceList)
        } else {
          list = this.sequenceList
        }
        this._resetCurrentIndex(list)
        this.setPlayList(list)
      },
      _resetCurrentIndex(list) {
        var that = this;
        let index = list.findIndex((item) => {
          return item.id === that.currentSong.id
        })
        this.setCurrentIndex(index)
      },
      getLyric() {
        this.currentSong.getLyric().then((lyric) => {
          this.currentLyric = new lyricParser(lyric,this.handleLyric)
          if(this.playing){
            this.currentLyric.play()
          }
        })
      },
      handleLyric({lineNum,txt}){
        this.currentLineNum = lineNum;
        if(lineNum>5){
          let lineEl = this.$refs.lyricLine[lineNum-5]
          this.$refs.lyricScroll.scrollToElement(lineEl,1000)
        }else{
          this.$refs.lyricScroll.scrollToElement(0,0,1000)
        }
      },
      recordStart(e){
        this.touch.initiated = true
        const touch = e.touches[0]
        this.touch.startX = touch.pageX
        this.touch.startY = touch.pageY
      },
      recordMove(e){
        if(!this.touch.initiated){
          return 
        }
        const touch = e.touches[0]
        const deltaX = touch.pageX-this.touch.startX
        const deltaY = touch.pageY-this.touch.startY
        //如果是纵向滚动不处理
        if(Math.abs(deltaY)>Math.abs(deltaX)){
          return
        }
        
        const left = this.currentShow==="cd"?0:-window.innerWidth
        const offsetwidth = Math.min(0,Math.max(-window.innerWidth,left+deltaX))
        this.touch.percent = Math.abs(offsetwidth/window.innerWidth)
        // console.log(offsetwidth)
        this.$refs.lyricScroll.$el.style[Transform]='translate3d('+offsetwidth+'px,0,0)'
      },
      recordEnd(e){
        let offsetwidth 
        if(this.currentShow==="cd"){
          if(this.touch.percent>0.3){
            console.log("111111")
            offsetwidth = -window.innerWidth
            this.currentShow ='lyric'
          }else{
            offsetwidth=0
          }
        }else{
          if(this.touch.percent<0.7){
            offsetwidth = 0
            this.currentShow ='cd'
          }else{
            offsetwidth = -window.innerWidth
          }
        }
         this.$refs.lyricScroll.$el.style[Transform]='translate3d('+offsetwidth+'px,0,0)'
      }
    },
    watch: {
      currentSong(newval, oldval) {
        if (newval.id === oldval.id) {
          return
        }
        this.$nextTick(() => {
          this.$refs.audio.play()
          this.getLyric()
        })
      },
      playing(newval) {
        const audio = this.$refs.audio
        this.$nextTick(() => {
          newval ? audio.play() : audio.pause()
        })
      }
    },
    computed: {
      ...mapGetters([
        'fullScreen',
        'playlist',
        "currentSong",
        "playing",
        "currentIndex",
        "mode",
        "sequenceList"
      ]),
      playIcon() {
        return this.playing ? 'pause' : 'play_arrow'
      },
      miniIcon() {
        return this.playing ? 'pause_circle_filled' : 'play_circle_filled'
      },
      cdCls() {
        return this.playing ? 'play' : 'play pause'
      },
      disableCls() {
        return this.songReady ? false : true
      },
      iconMode() {
        return this.mode === playMode.sequence ? 'queue_music' : this.mode === playMode.loop ? 'loop' : 'shuffle'
      }
    },
    created(){
      this.touch={}
    },
    components:{
      scroll
    }
  }

</script>
<style lang="scss" scoped>
  .player {
    .normal-player {
      position: fixed;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      background: #171717;
      z-index: 9999;
      .bg-filter {
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        background-size: auto 100%;
        background-repeat: no-repeat;
        background-position: center;
        filter: blur(10px);
        z-index: -1;
        opacity: 0.6;
      }
      .appbar-header {
        position: fixed;
        top: 0px;
        .mu-appbar-title {
          height: 100%;
        }
        .title {
          h3 {
            font-size: 18px;
            line-height: 26px;
            margin: 0;
            padding: 0;
            font-weight: 400;
          }
          p {
            font-size: 14px;
            line-height: 18px;
            margin: 0;
            padding: 0;
          }
        }
      }
      .normal-player-main {
        position: fixed;
        display: flex;
        flex-flow: column nowrap;
        justify-content: center;
        align-items: center;
        top: 56px;
        bottom: 0px;
        left: 0;
        right: 0;
        .song-wrap {
          width: 100%;
          flex-grow: 1;
          display: flex;
          position: relative;
          .record {
            position: absolute;
            width: 100%;
            top: 20px;
            bottom: 100px;
            text-align: center;
            white-space: nowrap;
            .record-right,
            .record-left {
              display: inline-block;
              width: 100%;
              height: 100%;
              vertical-align: top;
              overflow: hidden;
            }
            .song-disc {
              width: 80%;
              height: 296px;
              margin: 0 auto;
              position: relative;
              .song-turn {
                position: absolute;
                left: 0;
                right: 0;
                top: 0;
                bottom: 0;
                background-size: contain;
                &.play {
                  animation: rotate 20s linear infinite;
                }
                &.pause {
                  animation-play-state: paused
                }
                .song-img {
                  width: 184px;
                  height: 184px;
                  margin: -92px 0 0 -92px;
                  position: absolute;
                  left: 50%;
                  top: 50%;
                  border-radius: 50%;
                  overflow: hidden;
                  background-size: contain;

                  img {
                    width: 100%;
                  }
                }
              }
              .song-plybtn {
                position: absolute;
                left: 50%;
                top: 50%;
                height: 50px;
                width: 50px;
                transform: translate(-50%, -50%);
                z-index: 10;
                background-size: contain;
                background-repeat: no-repeat;
              }
            }
            .song-lyric{
              color:rgba(255,255,255,0.5);
              .current{
                color:#fff;
              }
            }
            
          }
          .song-slider {
            position: absolute;
            display: flex;
            flex-flow: row nowrap;
            width: 90%;
            bottom: 10px;
            left: 5%;
            align-items: center;
            .mu-slider {
              margin: 0;
            }
            p {
              padding: 0 12px;
            }
          }
        }
        .player-toolds {
          height: 60px;
          width: 100%;
          background: rgba(236, 236, 236, 0.3);
          .toolds {
            height: 100%;
            .flex-demo {
              text-align: center;
              color: #fff;
            }
          }
        }
      }
    }
    .mini-player {
      position: fixed;
      bottom: 0;
      left: 0;
      right: 0;
      height: 56px;
      z-index: 9999;
      .mini-flex {
        width: 100%;
        height: 100%;
        display: flex;
        flex-flow: row nowrap;
        .song-img {
          padding: 8px 20px;
          align-items: center;
          display: flex;
          justify-content: center;
          flex-flow: column nowrap;
          .play {
            animation: rotate 20s linear infinite;
          }
          .pause {
            animation-play-state: paused
          }
        }
        .song-info {
          display: flex;
          flex-flow: column nowrap;
          flex-grow: 1;
          justify-content: center;
          p {
            text-align: left;
            margin: 0;
            padding: 0;
            color: #000;
          }
        }
        .toolds {
          display: flex;
          align-items: center;
          color: #000;
        }
      }
    }
  }

  .normal-enter-active,
  .normal-leave-active {
    transition: all 0.4s;
    .appbar-header,
    .player-toolds {
      transition: all 0.4s;
    }
  }

  .normal-enter,
  .normal-leave-to {
    opacity: 0;
    .appbar-header {
      transform: translate3d(0, -100px, 0)
    }
    .player-toolds {
      transform: translate3d(0, 100px, 0)
    }
  }

  .mini-enter-active,
  .mini-leave-active {
    transition: all 0.4s;
  }

  .mini-enter,
  .mini-leave-to {
    opacity: 0;
    transform: translate3d(0, 100px, 0)
  }

  @keyframes rotate {
    0% {
      transform: rotate(0)
    }
    100% {
      transform: rotate(350deg)
    }
  }

</style>
